package com.erytech.linktalk.web.server;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.erytech.linktalk.dao.domain.Message;
import com.erytech.linktalk.dao.domain.User;
import com.erytech.linktalk.web.client.service.MessageInfo;
import com.erytech.linktalk.web.client.service.MessageRpcService;

public class MessageRpcServiceServlet extends BaseServlet implements
		MessageRpcService {
	
	Log logger = LogFactory.getLog(MessageRpcServiceServlet.class);
	
	public MessageInfo[] getMessages() {
		HttpSession session = getSession();
		User user = (User)session.getAttribute("user");
		if(user == null) {
			logger.warn("您还没有登录!");
			return new MessageInfo[0];
		}

		List messageList = getDaoFacade().getMessageDao().getMessageList(user);
		user.setLastPollTime(new Timestamp(System.currentTimeMillis()));
		getDaoFacade().getUserDao().updateUser(user);

		return toMessageInfoArray(messageList);
	}

	public void postMessage(MessageInfo messageInfo) {
		HttpSession session = getSession();
		User user = (User)session.getAttribute("user");
		if(user == null) {
			logger.warn("您还没有登录!");
			return;
		}
		Timestamp now = new Timestamp(System.currentTimeMillis());
		Message message = toMessage(messageInfo);
		message.setPostTime(now);
		getDaoFacade().getMessageDao().insertMessage(message);
		
		user.setLastPostTime(now);
		getDaoFacade().getUserDao().updateUser(user);
	}
	
	private MessageInfo[] toMessageInfoArray(List messageList) {
		List messageInfoList = new ArrayList(messageList.size());
		for (Object object : messageList) {
			messageInfoList.add(toMessageInfo((Message)object));
		}
		return (MessageInfo[])messageInfoList.toArray(new MessageInfo[messageInfoList.size()]);
	}

}
